package com.xbongbong.paas.help.factory.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.abstracts.AbstractOperatorFieldHandler;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.pojo.OperationsPojo;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.businessrule.pojo.BusinessRuleInfoPojo;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author 吴峰
 * @version v1.0
 * @date 2020/3/4 21:11
 * @since v1.0
 */
@Component
public class OperatorLinkDataMultiHandlerImpl extends AbstractOperatorFieldHandler {

    @Override
    public List<Integer> fieldType() {
        return Arrays.asList(FieldTypeEnum.LINK_DATA_MULTI.getType());
    }

    @Override
    public Object handlerTargetFormField(PaasFormDataEntity paasFormDataEntity, JSONObject data, FieldAttrEntity fieldAttrEntity, FieldAttrEntity targetField,
                                         BusinessRuleInfoPojo businessRuleInfoPojo, OperationsPojo operation) throws XbbException {
        if (Objects.nonNull(businessRuleInfoPojo.getObject())) {
            if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.LINK_DATA.getType()) || Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.DATAID.getType())) {
                JSONArray multiData = new JSONArray();
                multiData.add(businessRuleInfoPojo.getObject());
                return multiData;
            }
            return businessRuleInfoPojo.getObject();
        } else {
            if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.LINK_DATA.getType()) || Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.DATAID.getType())) {
                JSONArray multiData = new JSONArray();
                multiData.add(data.get(fieldAttrEntity.getAttr()));
                return multiData;
            }
            return data.get(fieldAttrEntity.getAttr());
        }
    }

    @Override
    public Object handlerFixedValue(FieldAttrEntity targetField, BusinessRuleInfoPojo businessRuleInfoPojo, OperationsPojo operation) throws XbbException {
        return null;
    }
}
